import { autoUpdater } from 'electron-updater'
import { ipcMain, app } from 'electron'

let mainWin: any = null
let judgeRs = {}
let isDownloading = false
const checkUpdate = (win) => {
  mainWin = win

  if (app.isPackaged) {
    // 它用于指示Electron应用程序是否已经被打包为一个可发布的应用
    autoUpdater.setFeedURL('http://localhost:8899/updater/')
  } else {
    autoUpdater.setFeedURL('http://localhost:8899/updater/')
  }
  autoUpdater.forceDevUpdateConfig = false //开发环境下强制更新
  autoUpdater.autoDownload = false // 自动下载
  autoUpdater.autoInstallOnAppQuit = true // 应用退出后自动安装
}

autoUpdater.on('update-available', (info) => {
  console.log('有新版本需要更新', info)
  judgeRs = {
    success: true,
    needUpdate: true,
    msg: '有新版本需要更新',
    version: info.version
  }
})
autoUpdater.on('update-not-available', (info) => {
  console.log('无需更新', info)
  judgeRs = {
    success: true,
    needUpdate: false,
    msg: '无需更新'
  }
})

// 监听渲染进程的 install 事件，触发退出应用并安装
ipcMain.handle('pc-install', () => autoUpdater.quitAndInstall())

ipcMain.handle('check-pc-update', async () => {
  try {
    if (isDownloading) {
      return {
        success: true,
        isDownloading: true,
        msg: '正在下载中，请稍后'
      }
    } else {
      const res = await autoUpdater.checkForUpdatesAndNotify()
      console.log('judge', res)
      //如果check结果正常，则使用上面监听构造的judgeRs
      return judgeRs
    }
  } catch (e) {
    //    check报错
    judgeRs = {
      success: false,
      msg: '没有更新包'
    }
    return judgeRs
  }
})
/*监听渲染进程指令，执行更新*/
ipcMain.handle('send-update', () => {
  autoUpdater.autoDownload = true
  mainWin.webContents.send('updateError', {
    data: '手动触发错误'
  })
  autoUpdater.downloadUpdate()
//   autoUpdater.checkForUpdates()
})
autoUpdater.on('download-progress', (prog) => {
  const speed =
    prog.bytesPerSecond / 1000000 > 1
      ? Math.ceil(prog.bytesPerSecond / 1000000) + 'M/s'
      : Math.ceil(prog.bytesPerSecond / 1000) + 'K/s'

  mainWin.webContents.send('pc-update-progress', {
    speed, // 网速
    percent: Math.ceil(prog.percent) // 百分比
  })
  isDownloading = true
})
autoUpdater.on('error', (err) => {
  mainWin.webContents.send('updateError', {
    data: err
  })
})
autoUpdater.on('update-downloaded', (info) => {
  console.log(info)
  isDownloading = false
  mainWin.webContents.send('pc-downloaded')
  // 下载完成后强制用户安装，不推荐
  // autoUpdater.quitAndInstall();
})

export default checkUpdate
